/*!
 * @file DFRobot_Sub_dht11.ino
 * @brief DFRobot's subscribe to dht11 data.
 * @n [Get the module here](http://www.dfrobot.com/index.php?route=product/product&product_id=1088)
 * @n This example subscribe to the data from the server.
 * @n [Connection and Diagram]
 *
 * @copyright	[DFRobot](http://www.dfrobot.com), 2016
 * @copyright	GNU Lesser General Public License
 *
 * @author [Wuxiao](Xiao.wu@dfrobot.com)
 * @version  V0.0.2
 * @date  2016-11-4
 */
#include <ESP8266WiFi.h>
#include "Iot.h"

WiFiClient client;

#define WLAN_SSID       "yourNetwork"      ///< your network SSID (name)
#define WLAN_PASS       "secretPassword"   ///< your network password

#ifdef ARDUINO_ESP8266_DFRobot_Education   ///< Choosing the condition, DFRobot server will be connected
#define AIO_USERNAME    "test"
#define AIO_KEY         "test"
Iot iot(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
#elif defined ARDUINO_ESP8266_DFRobot              ///< Choosing the condition, 10086 cloud server will be connected
#define AIO_USERNAME    "72833"
#define AIO_KEY    "sub123456"
#define AIO_CLIENTID    "3369569"
Iot iot(&client, AIO_SERVER, AIO_SERVERPORT, AIO_CLIENTID, AIO_USERNAME, AIO_KEY);
#endif

  /*!
   *  @brief Parse the data collected from the server.
   */
void subcallback(char *data, uint16_t len) {
  char recvmsg[100]={0};
  if(iot.parsejs(data))Serial.printf("parse ok\n");
  else return;
  if(iot.readAll(recvmsg,data,100)){       ///< If you do not know what msg about,use readAll to find msg
      Serial.printf("recvmsg = %s\n",recvmsg);
  }
  int tempVal = iot.readInt("Temp");
  Serial.printf("readInt temp = %d\n",tempVal);
  int humVal = iot.readInt("Hum");
  Serial.printf("readInt hum = %d\n",humVal);
}

void setup() {
  Serial.begin(115200);
  delay(10);
  Serial.println(F("DFrobot MQTT demo"));
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(WLAN_SSID);

  WiFi.begin(WLAN_SSID, WLAN_PASS);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  Serial.println("WiFi connected");
  Serial.println("IP address: "); 
  Serial.println(WiFi.localIP());
  
  /*!
   *  @brief set your's subscribe topic 
   */
  if(iot.subscribe("Dht11")){
	  Serial.printf("setSubscribe OK!\n");
  }
  
  /*!
   *  @brief set your's subcallback topic 
   */
  if(iot.setcallback("Dht11",subcallback)){
	  Serial.printf("set callbakc OK!\n");
  }
 
}

void loop() {
    if(iot.connected()){
		Serial.printf("already connected!\n");
	}else{
		iot.connect();  
	} 
    iot.available(1000);         ///< You can ste timeout
    delay(300);
}

